package com.tjyx.common.util;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;

/**
 * DTO工具类，用于动态构建DTO数据传输对象
 * 时间：2012-3-26
 * 
 * @author zhutianjie
 * @version v1.0
 *
 */
public class DTOUtil {

	/**
	 * 从请求中动态构建DTO类
	 * @param <T> DTO泛型
	 * @param clazz DTO类
	 * @param request HTTP请求
	 * @return
	 */
	public static <T> T createDTOFromRequest(Class<T> clazz, HttpServletRequest request) {
		T dto = null;
		try {
			dto = clazz.newInstance();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		Enumeration<String> attrEnum = request.getParameterNames();
		while (attrEnum.hasMoreElements()) {
			String fieldName = attrEnum.nextElement();
			String fieldValueStr = request.getParameter(fieldName);
			try {
				Field field = clazz.getDeclaredField(fieldName);
				Class<?> fieldType = field.getType();
				Method setMethod = ReflectUtil.createSetMethod(fieldName,
						clazz);
				if(fieldType != String.class) {
					/*
					 * 调用构造方法
					 */
					Constructor<?> constructor = fieldType.getDeclaredConstructor(String.class);
					Object requestValue = constructor.newInstance(fieldValueStr);
					setMethod.invoke(dto, requestValue);
				} else {
					setMethod.invoke(dto, fieldValueStr);
				}
			} catch (SecurityException e) {
				e.printStackTrace();
			} catch (NoSuchFieldException e) {
				e.printStackTrace();
			} catch (NoSuchMethodException e) {
				e.printStackTrace();
			} catch (InstantiationException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			}
		}
		return dto;
	}

}
